import subprocess
import random
import time

from common.gene_log import Get_Time


class RnDis():

    def __init__(self):
        self.web_list = ["39.156.69.79","58.250.137.36","123.126.55.41"]
        self.change_times = [i*50 for i in range(0,99999)]
        self.txt_name = Get_Time()

    def start_ping(self):
        a = 0
        b = 0
        c = 0
        # print(self.a)
        # print(self.change_times)
        try:
            while True:
                if c in self.change_times:
                    x = random.randint(0,2)
                    web_addr = self.web_list[x]
                    # print(web_addr)
                    rnids_cmd_obj = subprocess.Popen("ping "+ web_addr, shell=True, stdout=subprocess.PIPE,
                                     stderr=subprocess.STDOUT)
                c += 1
                time.sleep(1)
                # print(self.a)
                line = rnids_cmd_obj.stdout.readline(100).decode()
                now_time = Get_Time()
                print(now_time + "  >>>  " + line)
                with open("rndis_log/" + self.txt_name + ".txt", "a+") as f:
                    f.write(now_time + "  >>>  " + line)
                if "ping: unknown host" in line:
                    # print("未知网络")
                    b += 1
                elif "bytes of data" in line:
                    pass
                elif "ping: sendmsg: Network is unreachable" in line:
                    # print("当前网络不可达")
                    b += 1
                elif line == '':
                    # print("当前line为空")
                    pass
                else:
                    a += 1
                cons = "当前ping成功了%d次，失败了%d次" % (a, b)
                print(cons)
                with open("rndis_log/" + self.txt_name + ".txt", "a+") as f:
                    f.write(cons + "\r\n")
                continue
        except KeyboardInterrupt as e:
            print("rndis ping 已关闭")

# r = RnDis()
# r.start_ping()